package com.jzqf.bugly_plugin

import android.content.Context
import android.util.Log
import androidx.annotation.NonNull
import com.tencent.bugly.CrashModule
import com.tencent.bugly.crashreport.CrashReport
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar

/** BuglyPlugin */
class BuglyPlugin : FlutterPlugin, MethodCallHandler {

    private lateinit var channel: MethodChannel
    private var context: Context? = null
    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "bugly_plugin")
        channel.setMethodCallHandler(this)
        context = flutterPluginBinding.applicationContext
    }

    companion object {
        val TAG = "BuglyPlugin"

        @JvmStatic
        fun registerWith(registrar: Registrar) {
            val channel = MethodChannel(registrar.messenger(), "bugly_plugin")
            channel.setMethodCallHandler(BuglyPlugin())
        }
    }

    override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
        if (call.method == "getPlatformVersion") {
            result.success("Android ${android.os.Build.VERSION.RELEASE}")
        } else if (call.method == "setAppId") {
            val appId: String? = call.argument<String>("app_id")
            CrashReport.initCrashReport(context, appId, true)
            Log.i(TAG, "bugly 初始化 app_id=$appId,context:$context")
            result.success(CrashModule.getInstance().hasInitialized())
        } else if (call.method == "postException") {
            val error = call.argument<String>("error")
            val stack = call.argument<String>("stack")
            CrashReport.postException(4, "flutter exception", error, stack, null)
            result.success(true)
        } else {
            result.notImplemented()
        }
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }
}
